<template>
  <div>
      <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    
    <el-card>
      <!-- 头部搜索卡片视图 -->
      <el-row>
        <el-col :span="6">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="openadduserinfo">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 列表视图 -->
      <el-table :data="userlist" border stripe >
        <!-- stripe: 斑马条纹
        border：边框-->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!-- 操作栏 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" circle @click="showEditDialog(scope.row.id)">
            </el-button>
            <!-- 删除按钮 -->
              <el-button  type="danger"  icon="el-icon-delete"  size="mini"  circle  @click="removeUserById(scope.row.id)">
              </el-button>
              <!-- 权限分配 -->
            <el-tooltip class="item" effect="dark" content="角色分配" :enterable="false" placement="top">
              <el-button type="warning" icon="el-icon-setting" size="mini" circle @click="showSetRole(scope.row)">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能控件 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 3, 5, 8]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <!-- 添加用户对话框 -->
    <el-dialog
       title="添加用户"
       :visible.sync="adduserinfo"
       width="50%"
       :before-close="handleClose">
       <!-- 添加用户主题区域 -->
       <el-form :model="adduserform" status-icon :rules="adduserformrules" ref="adduserform"
        label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="adduserform.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="adduserform.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="adduserform.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="adduserform.mobile"></el-input>
          </el-form-item>
     </el-form>
       <span slot="footer" class="dialog-footer">
         <el-button @click="closedadduserinfo">取 消</el-button>
         <el-button type="primary" @click="submitadduserinfo">确 定</el-button>
       </span>
   </el-dialog>

   <!-- 编辑用户对话框 -->
   <el-dialog
       title="修改用户信息"
       :visible.sync="edituserinfo"
       width="50%"
       :before-close="handleClose">
       <!-- 编辑用户表单区域 -->
       <el-form :model="edituserform" status-icon :rules="edituserformrules"
        ref="edituserformrule" label-width="100px">
          <el-form-item label="用户名">
            <el-input v-model="edituserform.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="edituserform.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="edituserform.mobile"></el-input>
          </el-form-item>
     </el-form>
       <span slot="footer" class="dialog-footer">
         <el-button @click="closededituserinfo">取 消</el-button>
         <el-button type="primary" @click="submitedituserinfo">确 定</el-button>
       </span>
   </el-dialog>
      
      <!-- 权限分配对话框 -->
      <el-dialog title="用户权限分配" :visible.sync="setrightform" width="50%"
       :before-close="handleClose">
            <!-- 区域 -->
        <el-form :model="setrightuserinfo" status-icon :rules="setrightrules"
        ref="setrightrule" label-width="100px">
            <div>
              <p>用户名:<span disabled>{{setrightuserinfo.username}}</span></p>
              <p>角  色:<span>{{setrightuserinfo.role_name}}</span></p>
            </div>
            <el-form-item label="权限" props="power">
              <el-input v-model="setrightuserinfo.role_name"></el-input>
            </el-form-item>
        </el-form>
       <template slot="footer" class="dialog-footer">
         <el-button @click="removeright">取 消</el-button>
         <el-button @click="determineright" type="primary">确 定</el-button>
       </template>
   </el-dialog>

    </el-card>
  </div>
</template>

<script>
export default {
  name:'User',
  data(){
    // 自定义邮箱校验规则
    var checkemil=(rule,value,callback)=>{
         const regemil=/^\w+@\w+(\.\w+)+$/
         if(regemil.test(value)){return callback()}
         callback(new Error('邮箱格式不正确'));
    }
    // 自定义手机号规则
    var checkphone=(rule,value,callback)=>{
        const regphone=/^1[34578]\d{9}$/
        if(regphone.test(value)){return callback()}
        callback(new Error('手机号格式不正确'))
    }
      return{
        // 得到搜索输入字符
         queryInfo:{
           query:'',
          //  当前页码
           pagenum:1,
          //  显示条数
           pagesize:5
         },
        // 添加用户表单是否展开的判断 
        userlist:[],
        total:0,
        adduserinfo:false,
        adduserform:{
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        // 添加用户表单验证
        adduserformrules:{
          username:[
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {min: 2,max: 10,message: '用户名的长度在2～10个字',trigger: 'blur'}
        ],
          password:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            {min: 2,max: 20,message: '密码的长度在2～20个字',trigger: 'blur'}
          ],
          email:[
            { required: true, message: '请输入邮箱名', trigger: 'blur' },
            {validator:checkemil,trigger: 'blur'}
          ],
          mobile:[
            { required: true, message: '请输入手机号', trigger: 'blur' },
            {validator:checkphone,trigger: 'blur'}
          ]
        },
        // 编辑用户信息
        edituserform:{},
        edituserformrules:{
          email:[
            { required: true, message: '请输入邮箱名', trigger: 'blur' },
            {validator:checkemil,trigger: 'blur'}
          ],
          mobile:[
            { required: true, message: '请输入手机号', trigger: 'blur' },
            {validator:checkphone,trigger: 'blur'}
          ]
        },
        edituserinfo:false,
        // 分配权限对话框显示
        setrightform:false,
        setrightuserinfo:[],
        setrightrules:{
          power:[]
        }
      }
  },
  methods:{
    async getUserList(){
      // 请求users列表数据，解构赋值出来
      const {data:res}=await this.$http.get('users',{
        params:this.queryInfo
        })
      if(res.meta.status!=200){return this.$message.error(res.meta.msg)}
      this.userlist=res.data.users
      this.total=res.data.total
    //  console.log(res);
    },
    // 用户状态改变git
    async userStateChanged(row){
       const{data:res}=await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
       if(res.meta.status!=200){return this.$message.error(res.meta.msg)}
       this.$message.success(res.meta.msg)
    },
    // 修改编辑按钮
    async showEditDialog(rowid){
      this.edituserinfo=true
      const{data:res}=await this.$http.get(`users/${rowid}`)
      if(res.meta.status!==200){return this.$message.error('id查询用户失败')}
      this.$message.success(res.meta.msg)
      this.edituserform=res.data
    },
    // 删除用户数据按钮
    removeUserById(rowid){
      this.$confirm('确认删除')
          .then(async()=> { 
            const{data:res}=await this.$http.delete('users/'+rowid)
              if(res.meta.status!==200){return this.$message.error('删除用户失败')}
              this.$message.success(res.meta.msg)
              this.getUserList()
           })
          .catch(()=> {});
      
    },
    // 点击权限分配按钮
    showSetRole(row){
      this.setrightform=true
      this.setrightuserinfo=row
      console.log(row);
    },
    // 每页显示条数大小,pageSize 改变时会触发
    handleSizeChange(pagesize){
      this.queryInfo.pagesize=pagesize
      this.getUserList()
    },
    // 改变当前页码
    handleCurrentChange(newpage){
      this.queryInfo.pagenum=newpage
      this.getUserList()
    },
    // 打开添加用户对话款
    openadduserinfo(){
      this.adduserinfo=true
    },
    // 点击x 关闭前的回调，会暂停 Dialog 的关闭
    handleClose(done){
       this.$confirm('确认关闭？')
          .then(_ => { done() })
          .catch(_ => {});
    },
    // 添加用户点击确定提交
    submitadduserinfo(){
      this.$refs.adduserform.validate(async vaild=>{
        if(!vaild){return this.$message.error('添加用户失败,验证未通过')}
        const{data:res}=await this.$http.post('users',this.adduserform)
        if(res.meta.status!==201){return this.$message.error('添加用户失败')}
        this.$message.success(res.meta.msg)
        this.getUserList()
      })
      this.adduserinfo=false
      this.$refs.adduserform.resetFields()
    },
    // 取消添加用户对话款
    closedadduserinfo(){
      this.adduserinfo=false
      this.$refs.adduserform.resetFields()
    },
    // 编辑用户确定
    submitedituserinfo(){
      this.$refs.edituserformrule.validate(async valid=>{
        if(!valid){return this.$message.error('编辑失败')}
        const{data:res}=await this.$http.put(`users/${this.edituserform.id}`,{
        email:this.edituserform.email,
        mobile:this.edituserform.mobile
      })
      this.$message.success(res.meta.msg)
      this.getUserList()
      })
      
      this.edituserinfo=false
      this.$refs.edituserformrule.resetFields()
    },
    // 用户编辑取消
    closededituserinfo(){
      this.edituserinfo=false
      this.$refs.edituserformrule.resetFields()
    },
    // 确定权限分配
    determineright(){
      this.setrightform=false
    },
    // 取消权限分配
    removeright(){
      this.setrightform=false
    }
  },
  created(){
    this.getUserList()
  }
}
</script>

<style lang="less" scoped>
   .el-breadcrumb{
     margin: 0px 0 10px 0;
   }
</style>